package com.newly.center.auth.security;

import com.newly.common.base.constants.CommonConstant;
import com.newly.common.core.service.tenant.api.ITenantService;
import com.newly.common.core.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author gjm guan
 * @date 2021/8/18 18:03
 * @desc spring-security->UserDetailsService实现类，检验用户api接口访问权限
 */
@Component
@Slf4j
public class LoadUserDetails implements UserDetailsService {

    @Autowired
    private ITenantService tenantService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 得到登入用户类型
        String tenantType = (String) RequestUtils.getHeader(CommonConstant.USER_TYPE);
        TenantPo tenantPo = tenantService.getLoginTenant(username, tenantType);


        return new UserDetailsImpl(tenantPo.getUserName(), tenantPo.getPassword(), rolePerms);
    }

    public void demo() {
       /* String username = "";
        // 得到登入用户类型
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String tenantType = request.getHeader(CommonConstant.USER_TYPE);
        // 没带给默认值
        tenantType = StrUtil.isBlank(tenantType) ? CommonConstant.USER_TYPE_USER + "" : tenantType;

        // 查询用户
        TenantPo tenantPo = null;
        try {
            tenantPo = authInitService.getTenantByUserNameAntType(username, tenantType);
            Assert.notNull(tenantPo);
        } catch (Exception e) {
            log.error("登录失败，用户不存在：username = {} , e = {}", username, e);
            throw new NewlyException(CodeConstant.LOGIN_ERR, "用户名或密码错误！");
        }

        // 从redis中获取api授权对象
        List<ApiAuth> apiAuths = null;
        try {
            apiAuths = authInitService.cacheAuthApis(tenantPo.getId(), propertyCheck.isLoginCacheAuthApi());
        } catch (Exception e) {
            log.error("登录阶段->缓存[ID = {}]租户api授权对象失败", tenantPo.getId());
        }

        Assert.notNull(apiAuths, "[ID = {} , USERNAME = {}] , 登录失败,该租户无api授权对象数据，无法正常登录系统！", tenantPo.getId(), username);

        // 是否禁用了开发者
        if (authCheck.isRoleDev(apiAuths)) {
            if (!newlySysProperties.isOpenDev()) {
                log.error("开发者已被禁用，无法正常登录!");
                throw new NewlyException("开发者已被禁用，无法正常登录!");
            }
        }

        // 解析所有的角色与权限并去重
        List<String> rolePerms = authParse.parseRolePerm2Str(apiAuths);

        // 将用户存储至redis中
        TenantDto tenantDto = BeanUtil.copyProperties(tenantPo, TenantDto.class);
        newlyRedisUtils.setTenant(tenantDto.getUserName(), tenantDto, RedisKey.TENANT_EXPIRES_TIME_KEY);

        // 是否将data授权对象存储至redis中
        try {
            boolean loginCacheAuthData = propertyCheck.isLoginCacheAuthData();
            if (loginCacheAuthData) {
                authInitService.cacheDataAuths(tenantPo.getId(), loginCacheAuthData);
            }
        } catch (Exception e) {
            log.error("登录阶段->缓存[ID = {}]租户data授权对象失败", tenantPo.getId());
        }*/
    }
}
